package com.words.service.Impl;

import com.words.dao.UserDao;
import com.words.entity.User;
import com.words.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    //判断数据库中是否存在该用户
    public boolean login(User user) {
        User userDB = userDao.login(user.getUsername(),user.getPassword());

        return userDB != null;
    }

    @Override
    public boolean register(User user) {
        if(userDao.queryByUsername(user.getUsername())!=null){
            return false;
        }else {
            try{
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                String encodePasswod = encoder.encode(user.getPassword());
                userDao.register(user.getUsername(), encodePasswod);
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
            return true;
        }
    }

    @Override
    public boolean delete(String username) {
        if(userDao.queryByUsername(username)==null){
            return false;
        }else {
            try{
                userDao.delete(username);
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
            return true;
        }
    }

    @Override
    public User selectById(int id) {

        return userDao.queryById(id);
    }

    @Override
    public User selectByName(String username) {
        return userDao.queryByUsername(username);
    }

}
